package vikaa.timelinepackage;

import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import vikaa.tools.DialogService;
import vikaa.tools.HttpUtil;
import vikaa.tools.Logger;
import vikaa.tools.StringUtils;
import vikaa.ui.Mywowo;
import vikaa.ui.WeiboConstParam;
import vikaa.wowo.R;
import vikaa.wowo.cache.AuthoSharePreference;
import vikaa.wowo.cache.TimeLineSqlStoragePrivate;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class TimelineComment extends Activity implements OnItemClickListener{
	private ImageView avater;
	private TextView nicknameTv;
	private TextView created_at;
	private TextView textTv;
	private ImageView bmiddlePic;
	private LinearLayout contentLl;
	
	public static View topview;
	private ListView commentlist;
	private LinearLayout backBtn;
	private ImageView likeBtn;
	private EditText commentEdit;
	private ImageView sendBtn;
	private TextView countTv;
	public static String hash;
	public static String idstr;
	private String twitter_type;
	public static int count;
	public boolean  isLike;
	public static TimelineComment tlc;
	
	private ArrayList<Comment_item> tlitem = new ArrayList<Comment_item>();
	private ArrayList<Comment_item> itemlist = new ArrayList<Comment_item>();
	private AdapterCommentItem adapter ;
	public static int page;
	private boolean sended = false;
	 
	private LinearLayout ll;
	
	private InputMethodManager imm;
	
	private View loadingView;
	private RelativeLayout header;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.timeline_comment);
		imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
		tlc = this;
		initview();
		initdata();
		//imm.showSoftInputFromInputMethod(commentEdit.getApplicationWindowToken(), InputMethodManager.SHOW_IMPLICIT);
		/*if(getIntent().getExtras().getInt("com") == 1){
			Log.i("gfg", "jnn111");
			commentEdit.setFocusable(true);
			commentEdit.setFocusableInTouchMode(true);
			//imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED); 
		}*/
		commentEdit.setFocusable(true);
		commentEdit.setEnabled(true);
		commentEdit.setCursorVisible(true);
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				commentEdit.setFocusable(true);
				commentEdit.setFocusableInTouchMode(true);
				if(getIntent().getExtras().getInt("com") == 1){
					Message msg = mhandler.obtainMessage(9);
					msg.sendToTarget();
				}
			}
		}, 500); 
	}
	
	 
	
	private void initview(){
		//listview header
		topview = getLayoutInflater().inflate(R.layout.timeline_comment_header, null);  
		avater = (ImageView	)topview.findViewById(R.id.avater);
		nicknameTv = (TextView)topview.findViewById(R.id.nickname);
		created_at = (TextView)topview.findViewById(R.id.create);
		textTv = (TextView)topview.findViewById(R.id.text);
		bmiddlePic = (ImageView)topview.findViewById(R.id.bm_pic);
		contentLl = (LinearLayout)topview.findViewById(R.id.contentLl);
		countTv = (TextView)topview.findViewById(R.id.commentcount);
		
		loadingView = getLayoutInflater().inflate(R.layout.header_initialview, null); 
		header = (RelativeLayout)loadingView.findViewById(R.id.initialview);
		//listview
		commentlist = (ListView)findViewById(R.id.commentlist);
		commentlist.addHeaderView(topview);
		commentlist.addHeaderView(loadingView);
		adapter = new AdapterCommentItem(getLayoutInflater(), tlitem, getApplicationContext());
		commentlist.setAdapter(adapter);
		commentlist.setOnScrollListener(adapter);
		commentlist.setOnItemClickListener(this);
		//other view
		backBtn = (LinearLayout)findViewById(R.id.backBtn);
		backBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		likeBtn = (ImageView)findViewById(R.id.likeBtn);
		likeBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(!isLike){
					likeBtn.setImageResource(R.drawable.blackbutton_like_pressed);
					new TwitterLikeThread("twitter/like",hash,6).start();
				}
				//else
					//new TwitterLikeThread("twitter/unlike", hash, 7).start();
			}
		});
		commentEdit = (EditText)findViewById(R.id.commentcontent);
		commentEdit.addTextChangedListener(new TextWatcher() {
			private CharSequence temp;
	        private int editStart ;
	        private int editEnd ;
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				temp = s;
			}
			public void afterTextChanged(Editable s) {
				editStart = commentEdit.getSelectionStart();
	            editEnd = commentEdit.getSelectionEnd();
				if(commentEdit.getText().toString().length() > 140){
					s.delete(editStart-1, editEnd);
	                int tempSelection = editStart;
	                commentEdit.setText(s);
	                commentEdit.setSelection(tempSelection);
				}
			}
		});
		
		sendBtn = (ImageView)findViewById(R.id.send);
		sendBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				DialogService.hideSoftKeypad(TimelineComment.this);
				String content = commentEdit.getText().toString();
				content = StringUtils.spaceEdit(content);
				if(content.length() < 1 )
					DialogService.WarnDialog(TimelineComment.this, getString(R.string.tip), getString(R.string.tips_comment_null), getString(R.string.ok));
				else if(content.indexOf(":") != -1){
					int index = content.indexOf(":");
					String sub =content.substring(index+1, content.length());
					sub = StringUtils.spaceEdit(sub);
					if(sub.length() < 1)
						DialogService.WarnDialog(TimelineComment.this, getString(R.string.tip), getString(R.string.tips_comment_null), getString(R.string.ok));
					else{
						content =content.substring(0, index+1) + sub;
						if(Timeline.dynamicFlag){
							commentEdit.setText("");
							commentEdit.clearFocus();
							new CommentWBPostThread(content, idstr, 10).start();
						}
						else{
							commentEdit.setText("");
							commentEdit.clearFocus();
							new CommentPostThread(content, hash, 5).start();
						}
					}
				}
				else{
					if(Timeline.dynamicFlag){
						commentEdit.setText("");
						commentEdit.clearFocus();
						new CommentWBPostThread(content, idstr, 10).start();
					}
					else{
						commentEdit.setText("");
						commentEdit.clearFocus();
						new CommentPostThread(content, hash, 5).start();
					}
				}
			}
		});
		ll = (LinearLayout) findViewById(R.id.ll);
		ll.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				DialogService.hideSoftKeypad(TimelineComment.this);
				//commentEdit.clearFocus();
			}
		});
	}
	private void initdata(){
		String avater_url = getIntent().getStringExtra("avater");
		String nickname = getIntent().getStringExtra("nickname");
		String create = getIntent().getStringExtra("created_at");
		String bmiddle_pic_url = getIntent().getStringExtra("bmiddle_pic");
		hash = getIntent().getStringExtra("hash");
		if(hash.equals("0")){
			likeBtn.setVisibility(View.INVISIBLE);
		}
		idstr = getIntent().getStringExtra("idstr");
		twitter_type = getIntent().getStringExtra("twitter_type");
		String text = getIntent().getStringExtra("text");
		
		count = Integer.valueOf(getIntent().getStringExtra("comments_count"));
		isLike =getIntent().getStringExtra("isLike").equals("true") ? true: false;
		if(isLike){
			likeBtn.setImageResource(R.drawable.blackbutton_like_pressed);
		}
		if(StringUtils.isEmpty(avater_url)){
        	avater.setBackgroundResource(R.drawable.wowo_item_cover);
		}else{
        	AsyLoadImg.loadCircleAvater(HttpUtil.HttpUrlComplete(avater_url), avater);
        }
		nicknameTv.setText(nickname);
		SimpleDateFormat sdf= new SimpleDateFormat("MM/dd HH:mm");
        Date date = new Date(Long.valueOf(create)*1000);
		created_at.setText(sdf.format(date));
		if(StringUtils.isEmpty(bmiddle_pic_url)){
			bmiddlePic.setVisibility(View.GONE);
			contentLl.setVisibility(View.GONE);
        }else if(bmiddle_pic_url.indexOf("http") != -1){
        	AsyLoadImg.loadPic(bmiddle_pic_url, bmiddlePic);
        }else{
        	AsyLoadImg.loadPic(HttpUtil.HTTP_URL + bmiddle_pic_url, bmiddlePic);
        }
		if(StringUtils.isEmpty(text)){
			textTv.setVisibility(View.GONE);
		}else{
			textTv.setText(text);
		}
		countTv.setText("共"+count+"条评论");
		if(count != 0){
			page = 1;
			if(Timeline.dynamicFlag)
				new CommentWBThread(String.valueOf(page), idstr, 1).start();
			else
				new CommentThread(String.valueOf(page), hash, 1).start();
		}else{
			header.setVisibility(View.INVISIBLE);
		}
	}
	Handler mhandler = new Handler(){
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 1://first time load
				header.setVisibility(View.GONE);
				if(msg.obj != null){
					ArrayList<Comment_item> strings = (ArrayList<Comment_item>) msg.obj;
					if(!strings.isEmpty()){
						tlitem.addAll(strings);
						adapter.notifyDataSetChanged();
					}
				}
				break;
			case 2://go on load 
				adapter.ran = true;
				ArrayList<Comment_item> strings = (ArrayList<Comment_item>) msg.obj;
				if(!strings.isEmpty()){
					tlitem.addAll(strings);
					adapter.notifyDataSetChanged();
				}
				break;
			case 3:
				header.setVisibility(View.GONE);
				if(msg.obj != null){
					Toast.makeText(TimelineComment.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
				}
				else
					Toast.makeText(TimelineComment.this, R.string.server_crash, Toast.LENGTH_SHORT).show();
				break;
			case 4:
				header.setVisibility(View.GONE);
				Toast.makeText(TimelineComment.this, R.string.network_crash, Toast.LENGTH_SHORT).show();
				break;
			case 5:
				if(msg.obj != null){
					count += 1;
					countTv.setText("共"+count+"条评论");
					Comment_item item = (Comment_item) msg.obj;
					tlitem.add(0, item);
					TimeLineSqlStoragePrivate.updateTwitter(String.valueOf(count), hash, Timeline.space_id, TimelineComment.this);
					adapter.notifyDataSetChanged();
				}
				commentEdit.setText("");
				break;
			case 6://like
				isLike = true;
				likeBtn.setImageResource(R.drawable.blackbutton_like_pressed);
				Toast toast = new Toast(TimelineComment.this);
	        	toast = Toast.makeText(TimelineComment.this, "赞", 500);
	        	toast.setGravity(Gravity.CENTER, 0, 0);
	        	toast.show();
				break;
			case 7://unlike
				isLike = false;
				likeBtn.setImageResource(R.drawable.blackbutton_like_default);
				break;
			case 8:// softkey
				commentEdit.requestFocus();
				imm.toggleSoftInputFromWindow(commentEdit.getWindowToken(), 1, InputMethodManager.SHOW_FORCED);
				if(Integer.valueOf(msg.obj.toString()) > (adapter.getCount()-4)){
					getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
				}else{
					getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
				}
				commentlist.setSelectionFromTop(Integer.valueOf(msg.obj.toString()),Integer.valueOf(msg.obj.toString())-1);
				break;
			case 9:// softkey
				commentEdit.requestFocus();
				imm.toggleSoftInputFromWindow(commentEdit.getWindowToken(), 1, InputMethodManager.SHOW_FORCED);
				break;
			case 10:
				if(msg.obj != null){
					count += 1;
					countTv.setText("共"+count+"条评论");
					Comment_item item = (Comment_item) msg.obj;
					tlitem.add(0, item);
					//TimeLineSqlStoragePrivate.updateTwitter(String.valueOf(count), hash, Timeline.space_id, TimelineComment.this);
					adapter.notifyDataSetChanged();
				}
				commentEdit.setText("");
				commentEdit.clearFocus();
				break;
			}
		}
    };
	class CommentThread extends Thread{
    	private String page;
    	private String hash;
    	private int m;
    	boolean isrun = true;
		public CommentThread(String page, String hash, int m) {
			super();
			this.page = page;
			this.hash = hash;
			this.m = m;
		}
    	public void run() {
    		while(isrun){
    			isrun = false;
    			itemlist.clear();
    			Map<String, String> map = new HashMap<String, String>();
    			map.put("hash", hash);
    			map.put("page", page);
    			try {
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+"comment/load", map));
					if(jsonObj.getString("result").equals("1")){
						JSONArray jsonArr = jsonObj.getJSONArray("info");
						for(int i=0;i<jsonArr.length();i++){
							Comment_item item = new  Comment_item();
							item.setAvater(jsonArr.getJSONObject(i).getString("avatar"));
							item.setCreated_at(jsonArr.getJSONObject(i).getString("created_at"));
							item.setNickname(jsonArr.getJSONObject(i).getString("nickname"));
							//item.setAuthor(jsonArr.getJSONObject(i).getString("author"));
							item.setText(jsonArr.getJSONObject(i).getString("text"));
							itemlist.add(item);
						}
						Message msg = mhandler.obtainMessage(m);
						msg.obj = itemlist;
						msg.sendToTarget();
					}
					else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}
					else {
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
    		}
    	}
    }
	class CommentWBThread extends Thread{
    	private String page;
    	private String idstr ;
    	private int m;
    	boolean isrun = true;
		public CommentWBThread(String page, String idstr , int m) {
			super();
			this.page = page;
			this.idstr  = idstr ;
			this.m = m;
		}
    	public void run() {
    		while(isrun){
    			isrun = false;
    			itemlist.clear();
    			Map<String, String> map = new HashMap<String, String>();
    			map.put("id", idstr);
    			map.put("page", page);
    			map.put("twitter_type", twitter_type);
    			try {
    				//Logger.i(HttpUtil.postRequest(HttpUtil.BASE_URL+"comment/getweibocomment", map));
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+"comment/getweibocomment", map));
					if(jsonObj.getString("result").equals("1")){
						JSONArray jsonArr = jsonObj.getJSONArray("info");
						for(int i=0;i<jsonArr.length();i++){
							Comment_item item = new  Comment_item();
							item.setAvater(jsonArr.getJSONObject(i).getString("avatar"));
							item.setCreated_at(jsonArr.getJSONObject(i).getString("created_at"));
							item.setNickname(jsonArr.getJSONObject(i).getString("nickname"));
							//item.setAuthor(jsonArr.getJSONObject(i).getString("author"));
							item.setText(jsonArr.getJSONObject(i).getString("text"));
							itemlist.add(item);
						}
						Message msg = mhandler.obtainMessage(m);
						msg.obj = itemlist;
						msg.sendToTarget();
					}
					else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}
					else {
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
    		}
    	}
    }
	class CommentWBPostThread extends Thread{
    	private String text;
    	private String idstr ;
    	private int m;
    	boolean isrun = true;
		public CommentWBPostThread(String text, String idstr , int m) {
			super();
			this.text = text;
			this.idstr  = idstr ;
			this.m = m;
		}
    	public void run() {
    		while(isrun){
    			isrun = false;
    			itemlist.clear();
    			Map<String, String> map = new HashMap<String, String>();
    			map.put("id", idstr);
    			map.put("text", text);
    			map.put("twitter_type", twitter_type);
    			try {
    				
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+"comment/posttoweibo", map));
					if(jsonObj.getString("result").equals("1")){
						JSONObject jsonArr = jsonObj.getJSONObject("info");
							Comment_item item = new  Comment_item();
							item.setAvater(jsonArr.getString("avatar"));
							item.setCreated_at(jsonArr.getString("created_at"));
							item.setNickname(jsonArr.getString("nickname"));
							//item.setAuthor(jsonArr.getJSONObject(i).getString("author"));
							item.setText(jsonArr.getString("text"));
						Message msg = mhandler.obtainMessage(m);
						msg.obj = item;
						msg.sendToTarget();
					}
					else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}
					else {
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
    		}
    	}
    }
	class CommentPostThread extends Thread{
    	private String text;
    	private String hash;
    	private int m;
    	boolean isrun = true;
		public CommentPostThread(String text, String hash, int m) {
			super();
			this.text = text;
			this.hash = hash;
			this.m = m;
		}
    	public void run() {
    		while(isrun){
    			isrun = false;
    			Map<String, String> map = new HashMap<String, String>();
    			map.put("hash", hash);
    			map.put("text", text);
    			try {
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+"comment/post", map));
					if(jsonObj.getString("result").equals("1")){
						Comment_item item = new Comment_item();
						//item.setAuthor(jsonObj.getJSONObject("info").getString("author"));
						item.setAvater(jsonObj.getJSONObject("info").getString("avatar"));
						item.setCreated_at(jsonObj.getJSONObject("info").getString("created_at"));
						item.setNickname(jsonObj.getJSONObject("info").getString("nickname"));
						item.setText(jsonObj.getJSONObject("info").getString("text"));
						Message msg = mhandler.obtainMessage(m);
						msg.obj = item;
						msg.sendToTarget();
					}
					else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}
					else {
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
    		}
    	}
    }
	class TwitterLikeThread extends Thread{
		private String url;
    	private String hash;
    	private int m;
    	boolean isrun = true;
		public TwitterLikeThread(String url, String hash, int m) {
			super();
			this.url = url;
			this.hash = hash;
			this.m = m;
		}
    	public void run() {
    		while(isrun){
    			isrun = false;
    			Map<String, String> map = new HashMap<String, String>();
    			map.put("hash", hash);
    			try {
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+url, map));
					if(jsonObj.getString("result").equals("1")){
						Message msg = mhandler.obtainMessage(m);
						msg.sendToTarget();
					}
					else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}
					else {
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
    		}
    	}
	}
	public void onItemClick(AdapterView<?> arg0, View arg1, final int position, long arg3) {
		/*commentEdit.setText("回复@"+tlitem.get(position-2).getNickname()+":");
		commentEdit.setSelection(commentEdit.length());
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				commentEdit.setFocusable(true);
				commentEdit.setFocusableInTouchMode(true);
					Message msg = mhandler.obtainMessage(8);
					msg.obj = position;
					msg.sendToTarget();
			}
		}, 100);*/ 
		Intent intent = new Intent(TimelineComment.this,TimelineReply.class);
		intent.putExtra("tip", "回复@"+tlitem.get(position-2).getNickname()+":");
		intent.putExtra("idstr", idstr);
		intent.putExtra("hash", hash);
		intent.putExtra("twitter_type", twitter_type);
		startActivityForResult(intent, 10);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode != RESULT_OK)return;
		if(requestCode == 10){
			Bundle b = data.getExtras();  
			Comment_item item = new Comment_item();
			item.setAvater(b.getString("avater"));
			item.setCreated_at(b.getString("created_at"));
			item.setNickname(b.getString("nickname"));
			item.setText(b.getString("text"));
			int m = b.getInt("msg");
			Message msg = mhandler.obtainMessage(m);
			msg.obj = item;
			msg.sendToTarget();
		}
	}
	/*@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if(ev.getAction() == MotionEvent.ACTION_MOVE){
			DialogService.hideSoftKeypad(TimelineComment.this);
			commentEdit.clearFocus();
		}
		return super.dispatchTouchEvent(ev);
	}*/
}
